package main

type Hub struct {
	clients    map[*Client]bool //维护所有client
	broadcast  chan []byte      //广播消息
	register   chan *Client     //注册
	unregister chan *Client     //注销
}

func NewHub() *Hub {
	return &Hub{
		clients:    make(map[*Client]bool),
		broadcast:  make(chan []byte),
		register:   make(chan *Client),
		unregister: make(chan *Client),
	}
}

func (hub *Hub) Run() {
	for {
		select {
		case msg := <-hub.broadcast: //有消息需要广播
			for client := range hub.clients { //广播给每一个client
				select {
				case client.send <- msg:
				default: //异常处理逻辑，client挂了
					close(client.send)
					delete(hub.clients, client)
				}

			}
		case client := <-hub.register: //有人上线
			hub.clients[client] = true
		case client := <-hub.unregister: //注销
			if _, exists := hub.clients[client]; exists { //先判断是否已经注销过
				delete(hub.clients, client)
				close(client.send)
			}
		}
	}
}
